<template>
    <div>
        <nav-bar>
            <template v-slot:default>图书分类</template>
        </nav-bar>
        <div id="main-box">
            <div class="order-tab">
                <van-tabs v-model="active" @click="tabClick">
                    <van-tab title="销量"></van-tab>
                    <van-tab title="价格"></van-tab>
                    <van-tab title="评论数"></van-tab>
                </van-tabs>
            </div>
            <van-collapse class="left-menu" v-model="activeName" accordion>
                <van-collapse-item v-for="item in categories"
                                   :key="item.id"
                                   :title="item.name" :name="item.name">
                    <van-sidebar v-model="activeKey">
                        <van-sidebar-item v-for="sub in item.children"
                                          :key="sub.id"
                                          :title="sub.name"
                                          @click="getGoods(sub.id)"
                        />
                    </van-sidebar>
                </van-collapse-item>
            </van-collapse>
            <div class="good-list">
                <div class="content">
                    <van-card
                            v-for="item in showGoods" :key="item.id"
                            :num="item.comments_count"
                            :tag="item.comments_count>0?'热销':''"
                            :price="item.price"
                            :desc="item.updated_at"
                            :title="item.title"
                            :thumb="item.cover_url"
                            :lazy-load="true"
                            @click="itemClick(item.id)"
                    />
                </div>
            </div>
        </div>
        <back-top @goTop="goTop" v-show="isShowBackTop"></back-top>
    </div>
</template>

<script>
    import {computed, defineComponent, nextTick, onMounted, reactive, ref, watchEffect} from 'vue'
    import NavBar from 'components/common/navbar/NavBar'
    import {getCategory, getCategoryGoods} from "@/network/category";
    import BScroll from 'better-scroll'
    import BackTop from "@/components/common/backtop/BackTop";
    import {useRouter} from "vue-router";


    export default defineComponent({
        components: {
            NavBar,
            BackTop
        },
        setup() {

            const router = useRouter()

            let active = ref(3)
            let activeName = ref(1)
            let activeKey = ref(0)
            let categories = ref([])

            // 当前排序条件
            let currOrder = ref('sales')
            // 当前分类ID
            let currCid = ref(0)

            // 显示BackTop
            let isShowBackTop = ref(false)

            // 商品数据模型
            const goods = reactive({
                sales: {page: 1, list: []},
                price: {page: 1, list: []},
                comments_count: {page: 1, list: []}
            })

            // 计算属性获取当前显示那种类型的数据
            const showGoods = computed(() => {
                return goods[currOrder.value].list
            })

            // 获取数据
            const init = () => {
                getCategoryGoods(currOrder.value, currCid.value).then(res => {
                    // console.log(res.goods.data)
                    goods[currOrder.value].list = res.goods.data
                    // console.log(goods);
                })
            }

            // 滚动刷新
            let bscroll = reactive({})

            onMounted(() => {
                getCategory().then(res => {
                    // console.log(res)
                    categories.value = res.categories
                })
                init()

                // 创建BetterScroll对象
                bscroll = new BScroll(document.querySelector('.good-list'), {
                    probeType: 3,// 0,1,2,3(只要在滑动就处罚scroll)
                    click: true,// 滚动区域是否运行点击
                    pullUpLoad: true,// 上拉加载更多，默认false
                });
                // 触发滚动事件
                bscroll.on('scroll', (position) => {
                    // console.log(-position.y)
                    //isShowBackTop.value = true
                    isShowBackTop.value = -position.y > 500
                })
                // 上拉加载数据，触发pullingUp
                bscroll.on('pullingUp', () => {
                    // console.log('上拉加载更多...')
                    // console.log(`内容高度：${document.querySelector('.content').clientHeight}`);
                    const page = goods[currOrder.value].page + 1
                    // console.log(`当前类型：${currentType.value},当前page:${page}`);

                    getCategoryGoods(currOrder.value, currCid.value, page).then(res => {
                        goods[currOrder.value].list.push(...res.goods.data)
                        goods[currOrder.value].page += 1
                    })

                    // 完成上拉，等数据请求完成，要将新数据展示出来
                    bscroll.finishPullUp()
                    // 重新计算高度
                    bscroll.refresh()
                    // console.log(`内容高度：${document.querySelector('.content').clientHeight}`);
                })
            })

            // 监听任何一个变量有变化
            watchEffect(() => {
                nextTick(() => {
                    // 重新计算高度
                    bscroll && bscroll.refresh()
                })
            })

            // 排序选项卡
            const tabClick = (index) => {
                let orders = ['sales', 'price', 'comments_count']
                currOrder.value = orders[index]
                init()
                // 延迟重新计算高度
                nextTick(() => {
                    bscroll && bscroll.refresh()
                })
            }
            // 通过分类id查询商品
            const getGoods = (cid) => {
                currCid.value = cid
                init()
                // 延迟重新计算高度
                nextTick(() => {
                    bscroll && bscroll.refresh()
                })
                // console.log(currCid.value)
                // console.log(`排序序号：${currOrder.value}`);
            }
            // 返回顶部
            const goTop = () => {
                // console.log("返回顶部")
                bscroll.scrollTo(0, 0, 500)
            }
            // 点击方法
            const itemClick = (id) => {
                router.push({path:'/detail',query:{id}})
            }
            return {
                active,
                activeName,
                activeKey,
                categories,
                currOrder,
                currCid,
                tabClick,
                getGoods,
                showGoods,
                bscroll,
                goTop,
                isShowBackTop,
                itemClick,
                router
            }
        }
    })
</script>

<style lang="scss" scoped>
  #main-box {
    margin-top: 45px;
    display: flex;

    .order-tab {
      flex: 1;
      float: right;
      height: 50px;
      z-index: 9;
      position: fixed;
      top: 45px;
      right: 0;
      left: 130px;
    }

    .left-menu {
      position: fixed;
      top: 95px;
      left: 0;
      width: 130px;
    }

    .good-list {
      flex: 1;
      position: absolute;
      top: 100px;
      left: 130px;
      right: 0;
      height: 100vh;
      padding: 0;
      text-align: left !important;
    }
  }

  .van-card__thumb {
    width: 68px;
  }

</style>
